package com.ruoyi.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.service.Basic_FactoryService;
import com.ruoyi.entity.pojo.Basic_Factory;
import com.ruoyi.service.*;
import com.ruoyi.entity.pojo.*;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * AI智能客服控制器
 *
 * @author cjj
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*", maxAge = 3600)
public class CustomerServiceController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerServiceController.class);

    // 查询配置常量
    private static final int DEFAULT_QUERY_LIMIT = 10;
    private static final int MAX_QUERY_LIMIT = 50;

    private final ChatClient serviceChatClient;

    @Autowired
    private OpenAiChatModel openAiChatModel;

    @Autowired
    private Basic_FactoryService factoryService;

    @Autowired
    private ScProductionOrderService productionOrderService;

    @Autowired
    private ScWorkOrderService workOrderService;

    @Autowired
    private QcIqcService qcIqcService;

    @Autowired
    private CkStockDetailService stockDetailService;

    @Autowired
    private SbEquipmentService equipmentService;


    /**
     * AI智能客服对话接口
     */
    @GetMapping("/service")
    public Map<String, Object> service(@RequestParam String prompt, @RequestParam(required = false) String chatId) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("AI客服接收到用户提问: {}, 会话ID: {}", prompt, chatId);

            // 检查是否需要查询数据库
            String response;
            if (isDataQueryRequest(prompt)) {
                response = handleDataQuery(prompt);
            } else {
                // 请求AI模型并获取响应
                response = serviceChatClient
                        .prompt()
                        .user(prompt)
                        .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                        .call()
                        .content();
            }

            logger.info("AI客服响应完成，会话ID: {}", chatId);
            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", response);
            return result;
        } catch (Exception e) {
            logger.error("AI客服处理异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("msg", "AI服务暂时不可用，请稍后重试");
            result.put("data", null);
            return result;
        }
    }

    /**
     * 判断是否为数据查询请求
     */
    private boolean isDataQueryRequest(String prompt) {
        String lowerPrompt = prompt.toLowerCase();

        // 工厂相关查询
        boolean isFactoryQuery = lowerPrompt.contains("工厂") || lowerPrompt.contains("厂区");

        // 生产相关查询
        boolean isProductionQuery = lowerPrompt.contains("生产") || lowerPrompt.contains("工单") ||
                                   lowerPrompt.contains("派工") || lowerPrompt.contains("生产订单") ||
                                   lowerPrompt.contains("生产计划") || lowerPrompt.contains("工序");

        // 质检相关查询
        boolean isQualityQuery = lowerPrompt.contains("质检") || lowerPrompt.contains("质量") ||
                                lowerPrompt.contains("检验") || lowerPrompt.contains("不合格");

        // 库存相关查询
        boolean isInventoryQuery = lowerPrompt.contains("库存") || lowerPrompt.contains("物料") ||
                                  lowerPrompt.contains("仓库") || lowerPrompt.contains("入库") ||
                                  lowerPrompt.contains("出库") || lowerPrompt.contains("盘点");

        // 设备相关查询
        boolean isEquipmentQuery = lowerPrompt.contains("设备") || lowerPrompt.contains("机器") ||
                                  lowerPrompt.contains("维护") || lowerPrompt.contains("故障");

        // 通用查询关键词
        boolean hasQueryKeywords = lowerPrompt.contains("查询") || lowerPrompt.contains("显示") ||
                                  lowerPrompt.contains("列表") || lowerPrompt.contains("信息") ||
                                  lowerPrompt.contains("数据") || lowerPrompt.contains("统计") ||
                                  lowerPrompt.contains("报表");

        return (isFactoryQuery || isProductionQuery || isQualityQuery ||
                isInventoryQuery || isEquipmentQuery) && hasQueryKeywords;
    }

    /**
     * 处理数据查询请求
     */
    private String handleDataQuery(String prompt) {
        try {
            String lowerPrompt = prompt.toLowerCase();

            // 根据查询类型分发到不同的处理方法
            if (lowerPrompt.contains("工厂") || lowerPrompt.contains("厂区")) {
                return handleFactoryQuery(prompt);
            } else if (lowerPrompt.contains("生产") || lowerPrompt.contains("工单")) {
                return handleProductionQuery(prompt);
            } else if (lowerPrompt.contains("质检") || lowerPrompt.contains("质量")) {
                return handleQualityQuery(prompt);
            } else if (lowerPrompt.contains("库存") || lowerPrompt.contains("物料")) {
                return handleInventoryQuery(prompt);
            } else if (lowerPrompt.contains("设备")) {
                return handleEquipmentQuery(prompt);
            } else {
                // 默认查询工厂信息
                return handleFactoryQuery(prompt);
            }
        } catch (Exception e) {
            logger.error("处理数据查询异常: {}", e.getMessage(), e);
            return "查询数据时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理工厂信息查询
     */
    private String handleFactoryQuery(String prompt) {
        try {
            // 查询工厂数据（只查询未删除的记录）
            QueryWrapper<Basic_Factory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            List<Basic_Factory> factories = factoryService.list(queryWrapper);

            if (factories == null || factories.isEmpty()) {
                return "暂无工厂数据信息。";
            }

            // 构建表格格式的响应
            StringBuilder response = new StringBuilder();
            response.append("以下是查询到的工厂信息列表：\n\n");

            // 检查数据完整性，决定显示哪些列
            boolean hasCode = factories.stream().anyMatch(f -> f != null && f.getFactoryCode() != null && !f.getFactoryCode().trim().isEmpty());
            boolean hasName = factories.stream().anyMatch(f -> f != null && f.getFactoryName() != null && !f.getFactoryName().trim().isEmpty());
            boolean hasAddress = factories.stream().anyMatch(f -> f != null && f.getFactoryAddress() != null && !f.getFactoryAddress().trim().isEmpty());

            if (hasCode && hasName && hasAddress) {
                // 完整表格
                response.append("| 序号 | 工厂编号 | 工厂名称 | 工厂地址 | 备注说明 | 状态 |\n");
                response.append("|------|----------|----------|----------|----------|------|\n");
            } else {
                // 简化表格，只显示有数据的列
                response.append("| 序号 | 工厂ID | 备注说明 | 创建时间 | 状态 |\n");
                response.append("|------|--------|----------|----------|------|\n");
            }

            int validCount = 0;
            for (int i = 0; i < factories.size(); i++) {
                Basic_Factory factory = factories.get(i);
                // 跳过null对象
                if (factory == null) {
                    continue;
                }
                validCount++;

                if (hasCode && hasName && hasAddress) {
                    // 完整表格格式
                    response.append(String.format("| %d | %s | %s | %s | %s | %s |\n",
                        validCount,
                        factory.getFactoryCode() != null && !factory.getFactoryCode().trim().isEmpty() ? factory.getFactoryCode() : "未设置",
                        factory.getFactoryName() != null && !factory.getFactoryName().trim().isEmpty() ? factory.getFactoryName() : "未设置",
                        factory.getFactoryAddress() != null && !factory.getFactoryAddress().trim().isEmpty() ? factory.getFactoryAddress() : "未设置",
                        factory.getRemarks() != null && !factory.getRemarks().trim().isEmpty() ? factory.getRemarks() : "无",
                        "0".equals(factory.getIsDelete()) ? "正常" : "已删除"
                    ));
                } else {
                    // 简化表格格式
                    response.append(String.format("| %d | %s | %s | %s | %s |\n",
                        validCount,
                        factory.getFactoryId() != null ? factory.getFactoryId().toString() : "无",
                        factory.getRemarks() != null && !factory.getRemarks().trim().isEmpty() ? factory.getRemarks() : "无备注",
                        factory.getCreateTime() != null ? factory.getCreateTime().toLocalDate().toString() : "无",
                        "0".equals(factory.getIsDelete()) ? "正常" : "已删除"
                    ));
                }
            }

            // 添加数据统计信息
            response.append(String.format("\n📊 **数据统计**：共查询到 %d 条工厂记录\n", validCount));
            if (!hasCode || !hasName || !hasAddress) {
                response.append("\n⚠️ **提示**：部分工厂信息不完整，建议完善工厂编号、名称和地址信息。\n");
            }

            return response.toString();
        } catch (Exception e) {
            logger.error("查询工厂数据异常: {}", e.getMessage(), e);
            return "查询工厂数据时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理生产相关查询
     */
    private String handleProductionQuery(String prompt) {
        try {
            String lowerPrompt = prompt.toLowerCase();

            if (lowerPrompt.contains("生产订单") || lowerPrompt.contains("订单")) {
                return handleProductionOrderQuery();
            } else if (lowerPrompt.contains("工单")) {
                return handleWorkOrderQuery();
            } else {
                // 默认显示生产概览
                return handleProductionOverviewQuery();
            }
        } catch (Exception e) {
            logger.error("查询生产数据异常: {}", e.getMessage(), e);
            return "查询生产数据时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理生产订单查询
     */
    private String handleProductionOrderQuery() {
        try {
            QueryWrapper<ScProductionOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT " + getQueryLimit()); // 限制查询数量

            List<ScProductionOrder> orders = productionOrderService.list(queryWrapper);

            if (orders == null || orders.isEmpty()) {
                return "暂无生产订单数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是最近的生产订单信息：\n\n");
            response.append("| 序号 | 订单编号 | 销售订单ID | 生产状态 | 优先级 | 创建时间 | 备注 |\n");
            response.append("|------|----------|------------|----------|--------|----------|------|\n");

            for (int i = 0; i < orders.size(); i++) {
                ScProductionOrder order = orders.get(i);
                String statusText = getProductionOrderStatusText(order.getStatus());
                String priorityText = getPriorityText(order.getPriority());
                String createTimeStr = order.getCreateTime() != null ?
                    order.getCreateTime().toString().substring(0, 16) : "无";

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    order.getProdOrderCode() != null ? order.getProdOrderCode() : "无",
                    order.getSalesOrderId() != null ? order.getSalesOrderId().toString() : "无",
                    statusText,
                    priorityText,
                    createTimeStr,
                    order.getRemark() != null ? order.getRemark() : "无"
                ));
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 条生产订单记录\n", orders.size()));
            return response.toString();

        } catch (Exception e) {
            logger.error("查询生产订单异常: {}", e.getMessage(), e);
            return "查询生产订单时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理工单查询
     */
    private String handleWorkOrderQuery() {
        try {
            QueryWrapper<ScWorkOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT " + getQueryLimit());

            List<ScWorkOrder> workOrders = workOrderService.list(queryWrapper);

            if (workOrders == null || workOrders.isEmpty()) {
                return "暂无工单数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是最近的工单信息：\n\n");
            response.append("| 序号 | 工单编号 | 工单名称 | 产品ID | 数量 | 工单状态 | 车间ID | 计划开始时间 |\n");
            response.append("|------|----------|----------|--------|------|----------|--------|-------------|\n");

            for (int i = 0; i < workOrders.size(); i++) {
                ScWorkOrder workOrder = workOrders.get(i);
                String statusText = getWorkOrderStatusText(workOrder.getStatus());
                String planStartTimeStr = workOrder.getPlanStartTime() != null ?
                    workOrder.getPlanStartTime().toString().substring(0, 16) : "无";

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    workOrder.getWorkOrderCode() != null ? workOrder.getWorkOrderCode() : "无",
                    workOrder.getWorkOrderName() != null ? workOrder.getWorkOrderName() : "无",
                    workOrder.getProductId() != null ? workOrder.getProductId().toString() : "无",
                    workOrder.getQtyNum() != null ? workOrder.getQtyNum().toString() : "0",
                    statusText,
                    workOrder.getWorkshopId() != null ? workOrder.getWorkshopId().toString() : "无",
                    planStartTimeStr
                ));
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 条工单记录\n", workOrders.size()));
            return response.toString();

        } catch (Exception e) {
            logger.error("查询工单异常: {}", e.getMessage(), e);
            return "查询工单时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理生产概览查询
     */
    private String handleProductionOverviewQuery() {
        try {
            // 统计生产订单数量
            QueryWrapper<ScProductionOrder> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("is_delete", "0");
            long orderCount = productionOrderService.count(orderWrapper);

            // 统计工单数量
            QueryWrapper<ScWorkOrder> workOrderWrapper = new QueryWrapper<>();
            workOrderWrapper.eq("is_delete", "0");
            long workOrderCount = workOrderService.count(workOrderWrapper);

            StringBuilder response = new StringBuilder();
            response.append("📊 **生产管理数据概览**：\n\n");
            response.append("| 数据类型 | 数量 | 说明 |\n");
            response.append("|----------|------|------|\n");
            response.append(String.format("| 生产订单 | %d | 系统中的生产订单总数 |\n", orderCount));
            response.append(String.format("| 工单 | %d | 系统中的工单总数 |\n", workOrderCount));

            response.append("\n💡 **查询提示**：\n");
            response.append("- 输入\"生产订单查询\"可查看详细的生产订单列表\n");
            response.append("- 输入\"工单查询\"可查看详细的工单列表\n");
            response.append("- 输入\"生产进度查询\"可查看生产进度信息\n");

            return response.toString();

        } catch (Exception e) {
            logger.error("查询生产概览异常: {}", e.getMessage(), e);
            return "查询生产概览时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理质检相关查询
     */
    private String handleQualityQuery(String prompt) {
        try {
            String lowerPrompt = prompt.toLowerCase();

            if (lowerPrompt.contains("质检单") || lowerPrompt.contains("检验单")) {
                return handleQcInspectionQuery();
            } else if (lowerPrompt.contains("不合格") || lowerPrompt.contains("质量问题")) {
                return handleQcUnqualifiedQuery();
            } else {
                // 默认显示质检概览
                return handleQcOverviewQuery();
            }
        } catch (Exception e) {
            logger.error("查询质检数据异常: {}", e.getMessage(), e);
            return "查询质检数据时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理质检单查询
     */
    private String handleQcInspectionQuery() {
        try {
            QueryWrapper<QcIqc> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT " + getQueryLimit());

            List<QcIqc> inspections = qcIqcService.list(queryWrapper);

            if (inspections == null || inspections.isEmpty()) {
                return "暂无质检单数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是最近的质检单信息：\n\n");
            response.append("| 序号 | 检验单编号 | 检验单名称 | 供应商 | 货物名称 | 检测结果 | 检测日期 | 状态 |\n");
            response.append("|------|------------|------------|--------|----------|----------|----------|------|\n");

            for (int i = 0; i < inspections.size(); i++) {
                QcIqc inspection = inspections.get(i);
                String checkResultText = getCheckResultText(inspection.getCheckResult());
                String statusText = getQcStatusText(inspection.getStatus());
                String inspectDateStr = inspection.getInspectDate() != null ?
                    inspection.getInspectDate().toString().substring(0, 10) : "无";

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    inspection.getIqcCode() != null ? inspection.getIqcCode() : "无",
                    inspection.getIqcName() != null ? inspection.getIqcName() : "无",
                    inspection.getSupplierName() != null ? inspection.getSupplierName() : "无",
                    inspection.getGoodsName() != null ? inspection.getGoodsName() : "无",
                    checkResultText,
                    inspectDateStr,
                    statusText
                ));
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 条质检单记录\n", inspections.size()));
            return response.toString();

        } catch (Exception e) {
            logger.error("查询质检单异常: {}", e.getMessage(), e);
            return "查询质检单时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理不合格品查询
     */
    private String handleQcUnqualifiedQuery() {
        try {
            QueryWrapper<QcIqc> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.eq("check_result", "2"); // 2表示不合格
            queryWrapper.orderByDesc("inspect_date");
            queryWrapper.last("LIMIT " + getQueryLimit());

            List<QcIqc> unqualifiedItems = qcIqcService.list(queryWrapper);

            if (unqualifiedItems == null || unqualifiedItems.isEmpty()) {
                return "暂无不合格品数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是最近的不合格品信息：\n\n");
            response.append("| 序号 | 检验单编号 | 货物名称 | 供应商 | 不合格数 | 缺陷类型 | 检测日期 |\n");
            response.append("|------|------------|----------|--------|----------|----------|----------|\n");

            for (int i = 0; i < unqualifiedItems.size(); i++) {
                QcIqc item = unqualifiedItems.get(i);
                String inspectDateStr = item.getInspectDate() != null ?
                    item.getInspectDate().toString().substring(0, 10) : "无";

                String defectType = getDefectTypeText(item);

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    item.getIqcCode() != null ? item.getIqcCode() : "无",
                    item.getGoodsName() != null ? item.getGoodsName() : "无",
                    item.getSupplierName() != null ? item.getSupplierName() : "无",
                    item.getQuantityUnqualifiedNum() != null ? item.getQuantityUnqualifiedNum().toString() : "0",
                    defectType,
                    inspectDateStr
                ));
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 条不合格品记录\n", unqualifiedItems.size()));
            response.append("\n⚠️ **质量提醒**：请及时处理不合格品，分析原因并采取预防措施。\n");
            return response.toString();

        } catch (Exception e) {
            logger.error("查询不合格品异常: {}", e.getMessage(), e);
            return "查询不合格品时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理质检概览查询
     */
    private String handleQcOverviewQuery() {
        try {
            // 统计总质检单数量
            QueryWrapper<QcIqc> totalWrapper = new QueryWrapper<>();
            totalWrapper.eq("is_delete", "0");
            long totalCount = qcIqcService.count(totalWrapper);

            // 统计合格数量
            QueryWrapper<QcIqc> qualifiedWrapper = new QueryWrapper<>();
            qualifiedWrapper.eq("is_delete", "0");
            qualifiedWrapper.eq("check_result", "1");
            long qualifiedCount = qcIqcService.count(qualifiedWrapper);

            // 统计不合格数量
            QueryWrapper<QcIqc> unqualifiedWrapper = new QueryWrapper<>();
            unqualifiedWrapper.eq("is_delete", "0");
            unqualifiedWrapper.eq("check_result", "2");
            long unqualifiedCount = qcIqcService.count(unqualifiedWrapper);

            // 统计待检数量
            QueryWrapper<QcIqc> pendingWrapper = new QueryWrapper<>();
            pendingWrapper.eq("is_delete", "0");
            pendingWrapper.eq("check_result", "3");
            long pendingCount = qcIqcService.count(pendingWrapper);

            double qualifiedRate = totalCount > 0 ? (double) qualifiedCount / totalCount * 100 : 0;

            StringBuilder response = new StringBuilder();
            response.append("🔍 **质检管理数据概览**：\n\n");
            response.append("| 检测状态 | 数量 | 占比 | 说明 |\n");
            response.append("|----------|------|------|------|\n");
            response.append(String.format("| 总检测数 | %d | 100%% | 系统中的质检单总数 |\n", totalCount));
            response.append(String.format("| 合格 | %d | %.1f%% | 检测合格的数量 |\n", qualifiedCount, qualifiedRate));
            response.append(String.format("| 不合格 | %d | %.1f%% | 检测不合格的数量 |\n", unqualifiedCount, totalCount > 0 ? (double) unqualifiedCount / totalCount * 100 : 0));
            response.append(String.format("| 待检 | %d | %.1f%% | 等待检测的数量 |\n", pendingCount, totalCount > 0 ? (double) pendingCount / totalCount * 100 : 0));

            response.append("\n💡 **查询提示**：\n");
            response.append("- 输入\"质检单查询\"可查看详细的质检单列表\n");
            response.append("- 输入\"不合格品查询\"可查看不合格品详情\n");
            response.append("- 输入\"质量统计\"可查看质量分析报告\n");

            return response.toString();

        } catch (Exception e) {
            logger.error("查询质检概览异常: {}", e.getMessage(), e);
            return "查询质检概览时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理库存相关查询
     */
    private String handleInventoryQuery(String prompt) {
        try {
            String lowerPrompt = prompt.toLowerCase();

            if (lowerPrompt.contains("库存明细") || lowerPrompt.contains("库存查询")) {
                return handleStockDetailQuery();
            } else if (lowerPrompt.contains("物料") || lowerPrompt.contains("材料")) {
                return handleMaterialQuery();
            } else if (lowerPrompt.contains("库存预警") || lowerPrompt.contains("安全库存")) {
                return handleStockWarningQuery();
            } else {
                // 默认显示库存概览
                return handleInventoryOverviewQuery();
            }
        } catch (Exception e) {
            logger.error("查询库存数据异常: {}", e.getMessage(), e);
            return "查询库存数据时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理库存明细查询
     */
    private String handleStockDetailQuery() {
        try {
            QueryWrapper<CkStockDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT " + getQueryLimit(15));

            List<CkStockDetail> stockDetails = stockDetailService.list(queryWrapper);

            if (stockDetails == null || stockDetails.isEmpty()) {
                return "暂无库存明细数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是库存明细信息：\n\n");
            response.append("| 序号 | 物料编码 | 物料名称 | 库存数量 | 单位 | 仓库 | 库位 | 冻结状态 |\n");
            response.append("|------|----------|----------|----------|------|------|------|----------|\n");

            int validCount = 0;
            for (int i = 0; i < stockDetails.size(); i++) {
                CkStockDetail stock = stockDetails.get(i);

                // 跳过null对象
                if (stock == null) {
                    continue;
                }

                validCount++;
                String frozenText = "Y".equals(stock.getFrozen_flag()) ? "已冻结" : "正常";

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s | %s |\n",
                    validCount,
                    safeString(stock.getItem_code()),
                    safeString(stock.getItem_name()),
                    safeNumber(stock.getQuantity_num()),
                    safeString(stock.getUnit_name()),
                    safeString(stock.getWarehouse_name()),
                    safeString(stock.getArea_name()),
                    frozenText
                ));
            }

            if (validCount == 0) {
                return "暂无有效的库存明细数据。";
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 条库存明细记录\n", validCount));
            return response.toString();

        } catch (Exception e) {
            logger.error("查询库存明细异常: {}", e.getMessage(), e);
            return "查询库存明细时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理物料查询
     */
    private String handleMaterialQuery() {
        try {
            // 直接查询所有库存明细，然后在Java中去重
            QueryWrapper<CkStockDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.isNotNull("item_code");
            queryWrapper.ne("item_code", "");
            queryWrapper.orderBy(true, true, "item_code");
            queryWrapper.last("LIMIT " + getQueryLimit(50)); // 增加查询数量，后面去重

            List<CkStockDetail> allStocks = stockDetailService.list(queryWrapper);

            logger.info("查询到库存数据数量: {}", allStocks != null ? allStocks.size() : 0);

            if (allStocks == null || allStocks.isEmpty()) {
                return "暂无物料数据。";
            }

            // 在Java中进行去重，使用Set来存储已见过的物料编码
            Set<String> seenCodes = new HashSet<>();
            List<CkStockDetail> uniqueMaterials = new ArrayList<>();

            for (CkStockDetail stock : allStocks) {
                if (stock != null && stock.getItem_code() != null && !stock.getItem_code().trim().isEmpty()) {
                    String itemCode = stock.getItem_code().trim();
                    if (!seenCodes.contains(itemCode)) {
                        seenCodes.add(itemCode);
                        uniqueMaterials.add(stock);
                        // 限制返回数量
                        if (uniqueMaterials.size() >= getQueryLimit(15)) {
                            break;
                        }
                    }
                }
            }

            if (uniqueMaterials.isEmpty()) {
                return "暂无有效的物料数据。数据库中查询到 " + allStocks.size() + " 条记录，但都缺少必要的物料编码信息。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是物料信息：\n\n");
            response.append("| 序号 | 物料编码 | 物料名称 | 规格型号 | 单位 |\n");
            response.append("|------|----------|----------|----------|------|\n");

            for (int i = 0; i < uniqueMaterials.size(); i++) {
                CkStockDetail material = uniqueMaterials.get(i);

                response.append(String.format("| %d | %s | %s | %s | %s |\n",
                    i + 1,
                    safeString(material.getItem_code()),
                    safeString(material.getItem_name()),
                    safeString(material.getStock_sfn()),
                    safeString(material.getUnit_name())
                ));
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 种物料\n", uniqueMaterials.size()));
            return response.toString();

        } catch (Exception e) {
            logger.error("查询物料异常: {}", e.getMessage(), e);
            return "查询物料时发生错误：" + e.getMessage() + "，请稍后重试。";
        }
    }

    /**
     * 处理库存预警查询
     */
    private String handleStockWarningQuery() {
        try {
            // 查询库存数量较低的物料（假设小于10为低库存）
            QueryWrapper<CkStockDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.lt("quantity_num", 10);
            queryWrapper.orderByAsc("quantity_num");
            queryWrapper.last("LIMIT " + getQueryLimit());

            List<CkStockDetail> lowStockItems = stockDetailService.list(queryWrapper);

            if (lowStockItems == null || lowStockItems.isEmpty()) {
                return "暂无库存预警数据，所有物料库存充足。";
            }

            StringBuilder response = new StringBuilder();
            response.append("⚠️ **库存预警信息**：\n\n");
            response.append("| 序号 | 物料编码 | 物料名称 | 当前库存 | 单位 | 仓库 | 预警级别 |\n");
            response.append("|------|----------|----------|----------|------|------|----------|\n");

            int validCount = 0;
            for (int i = 0; i < lowStockItems.size(); i++) {
                CkStockDetail stock = lowStockItems.get(i);

                // 跳过null对象
                if (stock == null) {
                    continue;
                }

                validCount++;
                String warningLevel = getStockWarningLevel(stock.getQuantity_num());

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s |\n",
                    validCount,
                    safeString(stock.getItem_code()),
                    safeString(stock.getItem_name()),
                    safeNumber(stock.getQuantity_num()),
                    safeString(stock.getUnit_name()),
                    safeString(stock.getWarehouse_name()),
                    warningLevel
                ));
            }

            if (validCount == 0) {
                return "暂无库存预警数据，所有物料库存充足。";
            }

            response.append(String.format("\n📊 **预警统计**：共发现 %d 项库存预警\n", validCount));
            response.append("\n💡 **建议**：请及时补充库存不足的物料，避免影响生产。\n");
            return response.toString();

        } catch (Exception e) {
            logger.error("查询库存预警异常: {}", e.getMessage(), e);
            return "查询库存预警时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理库存概览查询
     */
    private String handleInventoryOverviewQuery() {
        try {
            // 统计库存总数
            QueryWrapper<CkStockDetail> totalWrapper = new QueryWrapper<>();
            totalWrapper.eq("is_delete", "0");
            long totalCount = stockDetailService.count(totalWrapper);

            // 统计冻结库存数量
            QueryWrapper<CkStockDetail> frozenWrapper = new QueryWrapper<>();
            frozenWrapper.eq("is_delete", "0");
            frozenWrapper.eq("frozen_flag", "Y");
            long frozenCount = stockDetailService.count(frozenWrapper);

            // 统计低库存数量
            QueryWrapper<CkStockDetail> lowStockWrapper = new QueryWrapper<>();
            lowStockWrapper.eq("is_delete", "0");
            lowStockWrapper.lt("quantity_num", 10);
            long lowStockCount = stockDetailService.count(lowStockWrapper);

            StringBuilder response = new StringBuilder();
            response.append("📦 **库存管理数据概览**：\n\n");
            response.append("| 库存状态 | 数量 | 说明 |\n");
            response.append("|----------|------|------|\n");
            response.append(String.format("| 总库存项目 | %d | 系统中的库存明细总数 |\n", totalCount));
            response.append(String.format("| 冻结库存 | %d | 被冻结无法使用的库存 |\n", frozenCount));
            response.append(String.format("| 低库存预警 | %d | 库存数量不足的物料 |\n", lowStockCount));
            response.append(String.format("| 正常库存 | %d | 库存充足的物料 |\n", totalCount - frozenCount - lowStockCount));

            response.append("\n💡 **查询提示**：\n");
            response.append("- 输入\"库存明细查询\"可查看详细的库存信息\n");
            response.append("- 输入\"物料查询\"可查看物料基础信息\n");
            response.append("- 输入\"库存预警\"可查看库存不足的物料\n");

            return response.toString();

        } catch (Exception e) {
            logger.error("查询库存概览异常: {}", e.getMessage(), e);
            return "查询库存概览时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理设备相关查询
     */
    private String handleEquipmentQuery(String prompt) {
        try {
            String lowerPrompt = prompt.toLowerCase();

            if (lowerPrompt.contains("设备状态") || lowerPrompt.contains("设备监控")) {
                return handleEquipmentStatusQuery();
            } else if (lowerPrompt.contains("维护") || lowerPrompt.contains("保养")) {
                return handleEquipmentMaintenanceQuery();
            } else if (lowerPrompt.contains("故障") || lowerPrompt.contains("维修")) {
                return handleEquipmentFaultQuery();
            } else {
                // 默认显示设备概览
                return handleEquipmentOverviewQuery();
            }
        } catch (Exception e) {
            logger.error("查询设备数据异常: {}", e.getMessage(), e);
            return "查询设备数据时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理设备状态查询
     */
    private String handleEquipmentStatusQuery() {
        try {
            QueryWrapper<SbEquipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT " + getQueryLimit(15));

            List<SbEquipment> equipments = equipmentService.list(queryWrapper);

            if (equipments == null || equipments.isEmpty()) {
                return "暂无设备数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是设备状态信息：\n\n");
            response.append("| 序号 | 设备编码 | 设备名称 | 设备类型 | 设备状态 | 车间 | 负责人 | 位置 |\n");
            response.append("|------|----------|----------|----------|----------|------|--------|------|\n");

            for (int i = 0; i < equipments.size(); i++) {
                SbEquipment equipment = equipments.get(i);
                String statusText = getEquipmentStatusText(equipment.getEquipmentStatus());

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    equipment.getEquipmentCode() != null ? equipment.getEquipmentCode() : "无",
                    equipment.getEquipmentName() != null ? equipment.getEquipmentName() : "无",
                    equipment.getEquipmentTypeName() != null ? equipment.getEquipmentTypeName() : "无",
                    statusText,
                    equipment.getWorkshop() != null ? equipment.getWorkshop() : "无",
                    equipment.getResponsiblePerson() != null ? equipment.getResponsiblePerson() : "无",
                    equipment.getLocation() != null ? equipment.getLocation() : "无"
                ));
            }

            response.append(String.format("\n📊 **数据统计**：共查询到 %d 台设备\n", equipments.size()));
            return response.toString();

        } catch (Exception e) {
            logger.error("查询设备状态异常: {}", e.getMessage(), e);
            return "查询设备状态时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理设备维护查询
     */
    private String handleEquipmentMaintenanceQuery() {
        try {
            // 查询需要维护的设备（假设根据保修期判断）
            QueryWrapper<SbEquipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.isNotNull("warranty_end_date");
            queryWrapper.orderByAsc("warranty_end_date");
            queryWrapper.last("LIMIT " + getQueryLimit());

            List<SbEquipment> equipments = equipmentService.list(queryWrapper);

            if (equipments == null || equipments.isEmpty()) {
                return "暂无设备维护数据。";
            }

            StringBuilder response = new StringBuilder();
            response.append("以下是设备维护信息：\n\n");
            response.append("| 序号 | 设备编码 | 设备名称 | 维护周期 | 保修结束日期 | 负责人 | 联系电话 |\n");
            response.append("|------|----------|----------|----------|--------------|--------|----------|\n");

            for (int i = 0; i < equipments.size(); i++) {
                SbEquipment equipment = equipments.get(i);
                String warrantyEndStr = equipment.getWarrantyEndDate() != null ?
                    equipment.getWarrantyEndDate().toString().substring(0, 10) : "无";

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    equipment.getEquipmentCode() != null ? equipment.getEquipmentCode() : "无",
                    equipment.getEquipmentName() != null ? equipment.getEquipmentName() : "无",
                    equipment.getMaintenanceCycle() != null ? equipment.getMaintenanceCycle() : "无",
                    warrantyEndStr,
                    equipment.getResponsiblePerson() != null ? equipment.getResponsiblePerson() : "无",
                    equipment.getContactPhone() != null ? equipment.getContactPhone() : "无"
                ));
            }

            response.append(String.format("\n📊 **维护统计**：共查询到 %d 台设备的维护信息\n", equipments.size()));
            response.append("\n💡 **提醒**：请按时进行设备维护保养，确保设备正常运行。\n");
            return response.toString();

        } catch (Exception e) {
            logger.error("查询设备维护异常: {}", e.getMessage(), e);
            return "查询设备维护时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理设备故障查询
     */
    private String handleEquipmentFaultQuery() {
        try {
            // 查询故障状态的设备
            QueryWrapper<SbEquipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            queryWrapper.eq("equipment_status", "2"); // 假设2表示维修中/故障
            queryWrapper.orderByDesc("update_time");

            List<SbEquipment> faultEquipments = equipmentService.list(queryWrapper);

            if (faultEquipments == null || faultEquipments.isEmpty()) {
                return "暂无设备故障记录，所有设备运行正常。";
            }

            StringBuilder response = new StringBuilder();
            response.append("⚠️ **设备故障信息**：\n\n");
            response.append("| 序号 | 设备编码 | 设备名称 | 设备状态 | 车间 | 负责人 | 更新时间 |\n");
            response.append("|------|----------|----------|----------|------|--------|----------|\n");

            for (int i = 0; i < faultEquipments.size(); i++) {
                SbEquipment equipment = faultEquipments.get(i);
                String statusText = getEquipmentStatusText(equipment.getEquipmentStatus());
                String updateTimeStr = equipment.getUpdateTime() != null ?
                    equipment.getUpdateTime().toString().substring(0, 16) : "无";

                response.append(String.format("| %d | %s | %s | %s | %s | %s | %s |\n",
                    i + 1,
                    equipment.getEquipmentCode() != null ? equipment.getEquipmentCode() : "无",
                    equipment.getEquipmentName() != null ? equipment.getEquipmentName() : "无",
                    statusText,
                    equipment.getWorkshop() != null ? equipment.getWorkshop() : "无",
                    equipment.getResponsiblePerson() != null ? equipment.getResponsiblePerson() : "无",
                    updateTimeStr
                ));
            }

            response.append(String.format("\n📊 **故障统计**：共发现 %d 台设备存在故障\n", faultEquipments.size()));
            response.append("\n🔧 **建议**：请及时处理故障设备，避免影响生产进度。\n");
            return response.toString();

        } catch (Exception e) {
            logger.error("查询设备故障异常: {}", e.getMessage(), e);
            return "查询设备故障时发生错误，请稍后重试。";
        }
    }

    /**
     * 处理设备概览查询
     */
    private String handleEquipmentOverviewQuery() {
        try {
            // 统计设备总数
            QueryWrapper<SbEquipment> totalWrapper = new QueryWrapper<>();
            totalWrapper.eq("is_delete", "0");
            long totalCount = equipmentService.count(totalWrapper);

            // 统计各状态设备数量
            QueryWrapper<SbEquipment> runningWrapper = new QueryWrapper<>();
            runningWrapper.eq("is_delete", "0");
            runningWrapper.eq("equipment_status", "1");
            long runningCount = equipmentService.count(runningWrapper);

            QueryWrapper<SbEquipment> faultWrapper = new QueryWrapper<>();
            faultWrapper.eq("is_delete", "0");
            faultWrapper.eq("equipment_status", "2");
            long faultCount = equipmentService.count(faultWrapper);

            QueryWrapper<SbEquipment> idleWrapper = new QueryWrapper<>();
            idleWrapper.eq("is_delete", "0");
            idleWrapper.eq("equipment_status", "0");
            long idleCount = equipmentService.count(idleWrapper);

            StringBuilder response = new StringBuilder();
            response.append("⚙️ **设备管理数据概览**：\n\n");
            response.append("| 设备状态 | 数量 | 占比 | 说明 |\n");
            response.append("|----------|------|------|------|\n");
            response.append(String.format("| 设备总数 | %d | 100%% | 系统中的设备总数 |\n", totalCount));
            response.append(String.format("| 运行中 | %d | %.1f%% | 正在运行的设备 |\n", runningCount, totalCount > 0 ? (double) runningCount / totalCount * 100 : 0));
            response.append(String.format("| 故障/维修 | %d | %.1f%% | 故障或维修中的设备 |\n", faultCount, totalCount > 0 ? (double) faultCount / totalCount * 100 : 0));
            response.append(String.format("| 空闲 | %d | %.1f%% | 空闲状态的设备 |\n", idleCount, totalCount > 0 ? (double) idleCount / totalCount * 100 : 0));

            response.append("\n💡 **查询提示**：\n");
            response.append("- 输入\"设备状态查询\"可查看详细的设备状态\n");
            response.append("- 输入\"设备维护查询\"可查看维护计划信息\n");
            response.append("- 输入\"设备故障查询\"可查看故障设备列表\n");

            return response.toString();

        } catch (Exception e) {
            logger.error("查询设备概览异常: {}", e.getMessage(), e);
            return "查询设备概览时发生错误，请稍后重试。";
        }
    }

    /**
     * 简单测试接口，不依赖AI模型
     */
    @GetMapping("/test")
    public Map<String, Object> test(@RequestParam(required = false) String message) {
        Map<String, Object> result = new HashMap<>();
        String responseText = "测试成功！您发送的消息是：" + (message != null ? message : "无消息") +
               "。当前时间：" + LocalDateTime.now();
        result.put("code", 200);
        result.put("msg", "success");
        result.put("data", responseText);
        return result;
    }

    /**
     * 获取工厂数据测试接口
     */
    @GetMapping("/getfactory")
    public Map<String, Object> getFactory() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Basic_Factory> factories = factoryService.list();
            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", factories);
            return result;
        } catch (Exception e) {
            logger.error("获取工厂数据异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("msg", "获取数据失败");
            result.put("data", null);
            return result;
        }
    }

    /**
     * 数据库连接测试接口
     */
    @GetMapping("/testdb")
    public Map<String, Object> testDatabase() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 测试原生SQL查询
            List<Basic_Factory> allFactories = factoryService.list();
            logger.info("查询到的工厂总数: {}", allFactories.size());

            StringBuilder resultText = new StringBuilder();
            resultText.append("数据库连接测试结果:\n");
            resultText.append("总记录数: ").append(allFactories.size()).append("\n\n");

            for (int i = 0; i < Math.min(allFactories.size(), 5); i++) {
                Basic_Factory factory = allFactories.get(i);
                if (factory != null) {
                    resultText.append("记录 ").append(i + 1).append(":\n");
                    resultText.append("  factory_id: ").append(factory.getFactoryId()).append("\n");
                    resultText.append("  factory_code: ").append(factory.getFactoryCode()).append("\n");
                    resultText.append("  factory_name: ").append(factory.getFactoryName()).append("\n");
                    resultText.append("  factory_address: ").append(factory.getFactoryAddress()).append("\n");
                    resultText.append("  remarks: ").append(factory.getRemarks()).append("\n");
                    resultText.append("  is_delete: ").append(factory.getIsDelete()).append("\n");
                    resultText.append("  create_time: ").append(factory.getCreateTime()).append("\n\n");
                } else {
                    resultText.append("记录 ").append(i + 1).append(": null\n\n");
                }
            }

            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", resultText.toString());
            return result;
        } catch (Exception e) {
            logger.error("数据库测试异常", e);
            result.put("code", 500);
            result.put("msg", "数据库测试失败: " + e.getMessage());
            result.put("data", null);
            return result;
        }
    }

    /**
     * 直接测试API连接
     */
    @RequestMapping(value = "/testapi", produces = "application/json;charset=utf-8")
    public String testApi() {
        try {
            // 使用Java原生HTTP客户端测试API
            java.net.http.HttpClient client = java.net.http.HttpClient.newHttpClient();

            String requestBody = """
                {
                    "model": "qwen-plus",
                    "messages": [
                        {"role": "user", "content": "你好"}
                    ]
                }
                """;

            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"))
                .header("Authorization", "Bearer sk-2f9aebec16914deb9a1572819c871c36")
                .header("Content-Type", "application/json")
                .POST(java.net.http.HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

            java.net.http.HttpResponse<String> response = client.send(request,
                java.net.http.HttpResponse.BodyHandlers.ofString());

            return "API测试结果：状态码=" + response.statusCode() + ", 响应=" + response.body();

        } catch (Exception e) {
            return "API测试失败：" + e.getMessage();
        }
    }

    /**
     * 测试SpringAI配置
     */
    @RequestMapping(value = "/testconfig", produces = "application/json;charset=utf-8")
    public String testConfig() {
        try {
            // 获取OpenAI模型的配置信息
            String baseUrl = openAiChatModel.getDefaultOptions().toString();
            return "SpringAI配置信息：" + baseUrl;
        } catch (Exception e) {
            return "SpringAI配置测试失败：" + e.getMessage();
        }
    }

    /**
     * 获取生产订单状态文本
     */
    private String getProductionOrderStatusText(String status) {
        if (status == null) return "未知";
        switch (status) {
            case "0": return "草稿";
            case "1": return "已提交";
            case "2": return "生产中";
            case "3": return "已完成";
            case "4": return "已取消";
            default: return "未知(" + status + ")";
        }
    }

    /**
     * 获取优先级文本
     */
    private String getPriorityText(String priority) {
        if (priority == null) return "普通";
        switch (priority) {
            case "1": return "低";
            case "2": return "普通";
            case "3": return "高";
            case "4": return "紧急";
            default: return "普通";
        }
    }

    /**
     * 获取工单状态文本
     */
    private String getWorkOrderStatusText(String status) {
        if (status == null) return "未知";
        switch (status) {
            case "0": return "待派工";
            case "1": return "已派工";
            case "2": return "生产中";
            case "3": return "已完成";
            case "4": return "已暂停";
            case "5": return "已取消";
            default: return "未知(" + status + ")";
        }
    }

    /**
     * 获取检测结果文本
     */
    private String getCheckResultText(String checkResult) {
        if (checkResult == null) return "未知";
        switch (checkResult) {
            case "1": return "合格";
            case "2": return "不合格";
            case "3": return "待检";
            default: return "未知(" + checkResult + ")";
        }
    }

    /**
     * 获取质检状态文本
     */
    private String getQcStatusText(String status) {
        if (status == null) return "未知";
        switch (status) {
            case "1": return "草稿";
            case "2": return "已提交";
            case "3": return "已审核";
            default: return "未知(" + status + ")";
        }
    }

    /**
     * 获取缺陷类型文本
     */
    private String getDefectTypeText(QcIqc item) {
        StringBuilder defectType = new StringBuilder();
        if (item.getCrQuantityNum() != null && item.getCrQuantityNum() > 0) {
            defectType.append("致命缺陷:").append(item.getCrQuantityNum()).append(" ");
        }
        if (item.getMajQuantityNum() != null && item.getMajQuantityNum() > 0) {
            defectType.append("严重缺陷:").append(item.getMajQuantityNum()).append(" ");
        }
        if (item.getMinQuantityNum() != null && item.getMinQuantityNum() > 0) {
            defectType.append("轻微缺陷:").append(item.getMinQuantityNum()).append(" ");
        }
        return defectType.length() > 0 ? defectType.toString().trim() : "无";
    }

    /**
     * 获取库存预警级别
     */
    private String getStockWarningLevel(java.math.BigDecimal quantity) {
        if (quantity == null) return "未知";
        double qty = quantity.doubleValue();
        if (qty <= 0) return "缺货";
        else if (qty <= 3) return "严重不足";
        else if (qty <= 5) return "不足";
        else if (qty <= 10) return "偏低";
        else return "正常";
    }

    /**
     * 获取设备状态文本
     */
    private String getEquipmentStatusText(String status) {
        if (status == null) return "未知";
        switch (status) {
            case "0": return "空闲";
            case "1": return "在用";
            case "2": return "维修中";
            case "3": return "报废";
            default: return "未知(" + status + ")";
        }
    }

    /**
     * 获取查询限制数量
     */
    private int getQueryLimit() {
        return DEFAULT_QUERY_LIMIT;
    }

    /**
     * 获取查询限制数量（可指定）
     */
    private int getQueryLimit(int limit) {
        return Math.min(limit, MAX_QUERY_LIMIT);
    }

    /**
     * 格式化日期字符串
     */
    private String formatDate(Date date) {
        if (date == null) return "无";
        return date.toString().substring(0, Math.min(16, date.toString().length()));
    }

    /**
     * 安全获取字符串值
     */
    private String safeString(String value) {
        return value != null && !value.trim().isEmpty() ? value : "无";
    }

    /**
     * 安全获取数字字符串
     */
    private String safeNumber(Object value) {
        return value != null ? value.toString() : "0";
    }

    /**
     * 构建统一的数据统计信息
     */
    private String buildDataStatistics(String dataType, int count) {
        return String.format("\n📊 **数据统计**：共查询到 %d 条%s记录", count, dataType);
    }

    /**
     * 构建统一的查询提示信息
     */
    private String buildQueryTips(String... tips) {
        if (tips == null || tips.length == 0) return "";

        StringBuilder sb = new StringBuilder();
        sb.append("\n💡 **查询提示**：\n");
        for (String tip : tips) {
            sb.append("- ").append(tip).append("\n");
        }
        return sb.toString();
    }

    /**
     * 构建统一的表格头部
     */
    private String buildTableHeader(String... headers) {
        if (headers == null || headers.length == 0) return "";

        StringBuilder sb = new StringBuilder();
        sb.append("| ");
        for (String header : headers) {
            sb.append(header).append(" | ");
        }
        sb.append("\n|");
        for (int i = 0; i < headers.length; i++) {
            sb.append("------|");
        }
        sb.append("\n");
        return sb.toString();
    }

    /**
     * 构建统一的表格行
     */
    private String buildTableRow(Object... values) {
        if (values == null || values.length == 0) return "";

        StringBuilder sb = new StringBuilder();
        sb.append("| ");
        for (Object value : values) {
            sb.append(value != null ? value.toString() : "无").append(" | ");
        }
        sb.append("\n");
        return sb.toString();
    }


}